package com.chlitina.store.modules.cash.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.utils.StringUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.service.CustomerService;
import com.chlitina.store.modules.base.service.StoreCareService;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.cash.entity.StoreConsume;
import com.chlitina.store.modules.cash.model.Member;
import com.chlitina.store.modules.cash.model.MemberPayResult;
import com.chlitina.store.modules.cash.model.MemberShoppingCart;
import com.chlitina.store.modules.cash.model.ShoppingPayment;
import com.chlitina.store.modules.cash.model.TabActive;
import com.chlitina.store.modules.cash.service.MemberService;
import com.chlitina.store.modules.cash.service.NomemberService;
import com.chlitina.store.modules.cash.service.StoreConsumeService;
import com.chlitina.store.modules.employee.dao.EmployeeDao;
import com.chlitina.store.modules.expert.entity.CustomerExam;
import com.chlitina.store.modules.expert.service.CustomerExamService;
import com.chlitina.store.modules.sms.quartz.CustomerTipQueueGenerate;
import com.chlitina.store.modules.sms.utils.SMSSend1;
import com.chlitina.store.modules.sys.utils.StoreUtils;

/**
 * Crash Controller
 * 
 * @author Songsong.xu
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/cash/member")
public class PaymentController extends BaseController {
	@Autowired
	private StoreConsumeService storeConsumeService;
	@Autowired
	private NomemberService nomemberService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private StoreCareService storeCareService;
	@Autowired
	private StoreProductService storeProductService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private CustomerExamService customerExamService;
	@Autowired
	private CustomerTipQueueGenerate customerTipQueueGenerate;
	static int TAB_ID_CARDS_TIMES = 0;
	static int TAB_ID_CARDS_DURATION = 1;
	static int TAB_ID_CARDS_PRODUCT = 2;
	static int TAB_ID_CARDS_ALL = 3;

	static int TAB_ID_NEWCARDS_PAYMENT_ALLCARD = 0;
	static int TAB_ID_NEWCARDS_PAYMENT_CASH = 1;

	static int TAB_ID_PRODUCT_PAYMENT_PRODUCTCARD = 0;
	static int TAB_ID_PRODUCT_PAYMENT_ALLCARD = 1;
	static int TAB_ID_PRODUCT_PAYMENT_CASH = 2;

	static int TAB_ID_PAYMENT_NEWCARDS = 0;
	static int TAB_ID_PAYMENT_RECHARGE = 1;
	static int TAB_ID_PAYMENT_PRODUCT = 2;

	public static interface KEY {
		String KEY_MEMBER = "member";
		String KEY_TAB_ACTIVE = "tabActive";
		String KEY_MESSAGE = "message";
	}

	public static interface URI {
		String URI_MEMBER_CONSUME = "modules/cash/cashMemberConsume";
		String URI_MEMBER_DETAIL = "modules/cash/cashMemberDetail";
		String URI_MEMBER_SHOPPING_DETAIL = "modules/cash/shoppingDetail";
		String URI_MEMBER_SHOPPING_DETAIL_DOCARE = "modules/cash/shoppingDetailDocare";
		String URI_MEMBER_SHOPPING_DETAIL_PRODUCT = "modules/cash/shoppingDetailProduct";
		String URI_MEMBER_SHOPPING_DETAIL_RECHARGE = "modules/cash/shoppingDetailRecharge";
		String URI_MEMBER_SHOPPING_DETAIL_GIFT = "modules/cash/shoppingDetailGift";

		String URI_MEMBER_SHOPPING_PAYMENT = "modules/cash/shoppingPayment";
		String URI_MEMBER_CARDS = "modules/cash/cashMemberCards";
		String URI_MEMBER_CARDS_NEW = "modules/cash/cashMemberCardsNew";
		String URI_MEMBER_SHOPPING_NEWCARDS = "modules/cash/cashMemberShoppingNewCards";
		String URI_MEMBER_BUY_PRODUCT = "modules/cash/cashMemberBuyProduct";
		String URI_MEMBER_DO_CARE = "modules/cash/cashMemberDoCare";
		String URI_MEMVER_SHOOPING_NEWCARDS_PAYMENT = "modules/cash/newcardsPayment";
		String URI_MEMVER_SHOOPING_PRODUCT_PAYMENT = "modules/cash/productPayment";
		String URI_MEMVER_SHOOPING_RECHARGE_PAYMENT = "modules/cash/rechargePayment";

	}

	@RequestMapping(value = { "shoppingDetails/newcards", "shoppingDetails" })
	public String shoppingDetails(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		member.updateMenuState();
		member.calculatePayment();
		if (member.getMenuState().isHasNewCards()) {
			return URI.URI_MEMBER_SHOPPING_DETAIL;
		}
		if (member.getMenuState().isHasRecharges()) {
			return URI.URI_MEMBER_SHOPPING_DETAIL_RECHARGE;
		}
		if (member.getMenuState().isHasProducts()
				|| member.getMenuState().isHasSolutionProduct()) {
			return URI.URI_MEMBER_SHOPPING_DETAIL_PRODUCT;
		}
		if (member.getMenuState().isHasCares()
				|| member.getMenuState().isHasSolutionCare()) {
			return URI.URI_MEMBER_SHOPPING_DETAIL_DOCARE;
		}

		if (member.getMenuState().isHasGifts()) {
			return URI.URI_MEMBER_SHOPPING_DETAIL_GIFT;
		} else {
			if (request.getParameter("back") != null) {
				return Global.getDirectURL("cash/member/detail?id="
						+ member.getCustomer().getId());
			}
			member.updateShoppingPayment();
			member.getNewCards().updateCardCount();
			return URI.URI_MEMBER_SHOPPING_PAYMENT;
		}
	}

	private Member getMember() {
		return StoreUtils.getMember();
	}

	@RequestMapping(value = { "shoppingDetails/product" })
	public String shoppingDetailsProduct(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		System.err.println(member.getPayment());
		return URI.URI_MEMBER_SHOPPING_DETAIL_PRODUCT;
	}

	@RequestMapping(value = { "shoppingDetails/recharge" })
	public String shoppingDetailsRecharge(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		return URI.URI_MEMBER_SHOPPING_DETAIL_RECHARGE;
	}

	@RequestMapping(value = { "shoppingDetails/docare" })
	public String shoppingDetailsDocare(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		return URI.URI_MEMBER_SHOPPING_DETAIL_DOCARE;
	}

	@RequestMapping(value = { "shoppingDetails/gift" })
	public String shoppingDetailsGift(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		return URI.URI_MEMBER_SHOPPING_DETAIL_GIFT;
	}

	@ResponseBody
	@RequestMapping(value = { "checkVerifyCode" })
	public String checkVerifyCode(HttpServletRequest request,
			HttpServletResponse response, Model model, String verifyCode) {
		response.setContentType("application/json; charset=UTF-8");
		List<String> result = new ArrayList<String>();
		Member member = getMember();
		if (member == null) {
			result.add("false");
			result.add("会员状态丢失");
		} else {
			String verify_Code = member.getShoppingCart().getStoreConsume()
					.getVerify_Code();
			if (verify_Code.equalsIgnoreCase(verifyCode)) {
				result.add("true");
				result.add("验证通过");
			} else {
				result.add("false");
				result.add("验证失败");
			}
		}
		return JsonMapper.getInstance().toJson(result);
	}

	@ResponseBody
	@RequestMapping(value = { "resendVerifyCode" })
	public String resendVerifyCode(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		response.setContentType("application/json; charset=UTF-8");
		List<String> result = new ArrayList<String>();
		Member member = getMember();
		if (member == null) {
			result.add("false");
			result.add("会员状态丢失");
		} else {
			member.getShoppingCart().getStoreConsume()
					.setVerify_Code(StringUtils.generateVerifyCode());
			StringBuilder sb = new StringBuilder();
			sb.append("您本次消费的校验码为")
					.append(member.getShoppingCart().getStoreConsume()
							.getVerify_Code()).append(", 请勿向任何人提供您收到的短信校验码");
			boolean state = false;
			if (!isDebug()) {
				String send = null;
				try {
					send = SMSSend1.send(member.getCustomer().getMobile(),
							sb.toString());
					System.err.println(send);
					state = true;
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				System.err.println(sb);
				state = true;
			}
			result.add(state + "");
			result.add(member.getShoppingCart().getStoreConsume()
					.getVerify_Code());
		}
		return result.toString();
	}

	boolean isDebug() {// TODO
		return false;
	}

	/**
	 * Consume detail page
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "consumeDetailPage" })
	public String consumeDetailPage(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		String consumeID = request.getParameter("consumeID");
		if (consumeID == null) {
			addMessage(redirectAttributes, "状态丢失");
			// return getDirectURL("nonmember");
		}
		try {
			long cID = Long.parseLong(consumeID);
			String jsonData = memberService.findMemberConsumeDetail(cID);
			model.addAttribute("jsonData", jsonData);
		} catch (NumberFormatException e) {
			addMessage(redirectAttributes, "状态丢失");
			// return getDirectURL("nonmember");
		}
		return null;
	}

	@RequestMapping(value = { "shoppingFinish" })
	public String shoppingFinish(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		model.addAttribute("member", member);
		String cashMoneyStr = request.getParameter("cashMoney");
		float cashMoney = Float.parseFloat(cashMoneyStr);
		ShoppingPayment payment = member.getPayment();
		payment.setPay(cashMoney);
		if (payment.getTotal() - cashMoney < 0) {
			model.addAttribute("message", "错误的支付金额");

			return URI.URI_MEMBER_SHOPPING_PAYMENT;
		}

		member.getPayment().setDebt(payment.getTotal() - cashMoney);
		MemberPayResult memberPayResult = new MemberPayResult();
		StoreConsume consume = memberService.payfor(member, memberPayResult);
		if (consume == null) {
			model.addAttribute("message", "结账过程中出错");
			return URI.URI_MEMBER_SHOPPING_PAYMENT;
		} else {
			MemberShoppingCart shoppingCart = member.getShoppingCart();
			if (!shoppingCart.getSolutionCares().isEmpty()
					|| !shoppingCart.getSolutionProducts().isEmpty()) {
				// 生产提醒短信
				customerTipQueueGenerate.generate(member);
				// update examState
				CustomerExam customerExam = shoppingCart.getCustomerExam();
				if (customerExam != null) {
					customerExam = customerExamService
							.get(customerExam.getId());
					customerExam.setStoreConsume(consume);
					customerExamService.save(customerExam);
				}
			}
			String content = "亲爱的克缇佳人{customer}，您在{store}消费结单成功。克缇适时，适量，适性的专业指导，会随时在您身边，为您的美丽加分助力。我们一起~让时光停在最美的地方。";
			content = content.replace("{customer}", member.getCustomer()
					.getName());
			content = content.replace("{store}", StoreUtils.getStore()
					.getName());
			customerTipQueueGenerate.immediateSend(member.getCustomer()
					.getMobile(), content);
			StoreUtils.removeMember();
			request.getSession().removeAttribute(KEY.KEY_MEMBER);
			addMessage(redirectAttributes, "结账成功");
			System.err.println("结算结果："+memberPayResult.getReturnCash() +"\n"+memberPayResult.getBuyProductFailed());
			return Global.getDirectURL("base/customer/consumeDetail?consumeId="
					+ consume.getId() + "&target=cash/member");
		}
	}

	@RequestMapping(value = { "shoppingPayment" })
	public String shoppingPayment(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		if (!member.canFinish()) {
			model.addAttribute(KEY.KEY_MESSAGE, "有尚未结算的产品， 请先设置结算方式");
			return URI.URI_MEMBER_SHOPPING_DETAIL;
		}
		model.addAttribute("member", member);
		member.updateShoppingPayment();
		member.getNewCards().updateCardCount();
		return URI.URI_MEMBER_SHOPPING_PAYMENT;
	}

	@RequestMapping(value = { "shopping/newCards" })
	public String shoppingNewCards(TabActive tabActive,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		tabActive.setId(TAB_ID_CARDS_TIMES);
		model.addAttribute(KEY.KEY_TAB_ACTIVE, tabActive);
		return URI.URI_MEMBER_SHOPPING_NEWCARDS;
	}

}
